<?php

namespace app\admin\service\dev;

use app\admin\model\dev\Prop as PropModel;
use think\facade\Db;

class PropService
{

    public static function getActionTypeDefault(): array
    {
        $list = Db::name('dev_prop')
            ->field('value,config')
            ->json(['config'])
            ->where('type', '=', 'action')
            ->where('status', '=', 1)
            ->column('config', 'value');
        return $list;
    }


    /**
     * 获取各个字段类型的默认值
     * @return array
     */
    public static function getFieldTypeDefault(): array
    {
        $list = Db::name('dev_prop')->field('value,config')
            ->json(['config'])
            ->where('type', '=', 'field')
            ->where('status', '=', 1)
            ->column('config','value');
        return $list;
    }

    public static function getPropList(array $params): array
    {
        $fields = FieldService::getIndexFields('DevProp');

        $query = PropModel::withPerms()->field($fields);

        self::applySearchFilters($query, $params);

        $orderBy = sort_rules($params['order_by'] ?? 'sort|asc');

        $query->order($orderBy);

        $pageSize = $params['page_size'] ?? 10;

        $currentPage = $params['current_page'] ?? 1;

        $list = $query->paginate($pageSize, $currentPage)->toArray();

        $list['sort'] = $orderBy;

        return $list;

    }

    private static function applySearchFilters($query, array $params): void
    {
        $query->when(isset($params['keyword']), function ($q) use ($params) {
            $keyword = str_replace(['%', '_'], ['\%', '\_'], $params['keyword']);
            $q->where('label|value', 'like', '%' . $keyword . '%');
        });

        $query->when(isset($params['type']), function ($q) use ($params) {
            $q->where('type', '=', $params['type']);
        });

        $query->when(isset($params['for_template']), function ($q) use ($params) {
            $q->where('for_template', '=', $params['for_template']);
        });

        $query->when(isset($params['status']), function ($q) use ($params) {
            $q->where('status', '=', $params['status']);
        });
    }

}